/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.network;
import java.io.*;
import java.net.*;
import com.cse.p2p.common.*;
/**
 *
 * @author TuyetNgan
 */
public class ServerTaskData extends Thread {
        private File file;
        private InputStream is = null;
        private ServerSocket serverSocket = null;
        private int portData = 2000;
        private Socket socket = null;
        
        public ServerTaskData(File f) {
            this.file = f;
        }
        public void  newConnection(){
            try {
                serverSocket = new ServerSocket(portData);
                socket = serverSocket.accept();
            } catch (IOException e) {
                System.err.println("Could not listen on port: " + portData);
                System.exit(-1);
            }
            try{
                is = socket.getInputStream();
            }
            catch(IOException e){}
        }
        public void closeConnection(){
			try {
                serverSocket.close();
                socket.close();
			}
			catch (IOException e){}
        }
        
        @Override
        public void run() {
            newConnection();
            System.out.println("Server receiving ... ");
            /* receive file from client */
            try {
                byte[] mybytearray = new byte[server.logic.ServerLogicImplement.choosePiecesSize()];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                int bytesRead;
                int count = 0;
                while((bytesRead = is.read(mybytearray, 0, mybytearray.length)) != -1){
                    System.out.println(count++);
                    bos.write(mybytearray, 0, bytesRead);
                }
                bos.close();
                System.out.println("Server receive all");
            } catch (EOFException ex) {}
            catch (UnknownHostException i){}
            catch (IOException i){}
            closeConnection();
        }
    
    
    
    
    
    
    
}
